package com.waidi.clothespad.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

/**
 * 通用适配器，继承此类，子类只需要复写convert方法
 * @author lkw
 *
 * @param <T>
 */
public abstract class CommonAdapter<T> extends BaseAdapter
{
	protected LayoutInflater mInflater;
	protected Context mContext;
	protected List<T> mDatas;
	protected final int mItemLayoutId;
	protected int position;

	public CommonAdapter(Context context, List<T> mDatas, int itemLayoutId)
	{
		this.mContext = context;
		this.mInflater = LayoutInflater.from(mContext);
		this.mDatas = mDatas;
		this.mItemLayoutId = itemLayoutId;
	}

	@Override
	public int getCount()
	{
		return mDatas.size();
	}

	@Override
	public T getItem(int position)
	{
		return mDatas.get(position);
	}

	public List<T> getmList() {
		return mDatas;
	}

	public void setmDatas(List<T> mDatas) {
		this.mDatas = mDatas;
	}

	@Override
	public long getItemId(int position)
	{
		return position;
	}
	
	/**
	 * 添加多条记录
	 * @param itemList
	 */
	public void addItemList(List<T> itemList){
		mDatas.addAll(itemList);
	}
	

	/**
	 * 添加单条记录
	 * @param item
	 */
	public void addItem(T item){
		mDatas.add(item);
	}
	
	public void addOrUpdateItem(T item){
		int index = mDatas.indexOf(item);
		if (index != -1) {
			mDatas.remove(index);
			mDatas.add(index, item);
		}else{
			mDatas.add(item);
		}
	}
	
	/**
	 * 更改list集合里面的一条记录
	 * @param item
	 * @param postion 要更改的条目在集合中的位置
	 */
	public void updataItem(T item,int postion){
		mDatas.remove(postion);
		mDatas.add(postion, item);
	}
	
	/**
	 * 删除
	 */
	public void removeItem(int position){
		mDatas.remove(position);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		final ViewHolder viewHolder = getViewHolder(position, convertView,
				parent);
		convert(viewHolder, getItem(position));
		return viewHolder.getConvertView();

	}

	public abstract void convert(ViewHolder helper, T item);

	private ViewHolder getViewHolder(int position, View convertView,
			ViewGroup parent)
	{
		return ViewHolder.get(mContext, convertView, parent, mItemLayoutId,
				position);
	}
	
}
